from apps import jsonrpc_v1
from .models import db, NewsCategory, News


@jsonrpc_v1.method("News.news_category")
def news_category():
	"""文章分类"""
	category_list = NewsCategory.query.filter(
		NewsCategory.is_show == True,
		NewsCategory.is_deleted == False
	).order_by(
		NewsCategory.sort.asc(),
		NewsCategory.id.desc()
	).limit(6).all()

	data = []

	for category in category_list:
		data.append(category.__to_dict__(["id", "name"]))

	return data


@jsonrpc_v1.method("News.home_news")
def home_news():
	"""首页潮流资讯推荐文章"""
	news_list = News.query.filter(
		News.is_recommend == True,
		News.is_show == True,
		News.is_deleted == False
	).order_by(
		News.sort.asc(),
		News.id.desc()
	).limit(5).all()

	data = []
	for news in news_list:
		data.append(news.__to_dict__(["id", "title", "read_count", "descript", "created_time", "image_url"]))

	return data


@jsonrpc_v1.method("News.list_news(category=Number, page=Number, size=Number)")
def list_news(category=0, page=1, size=10):
	"""列表页文章列表"""
	data = {}
	try:
		query = News.query.filter(
			News.is_show == True,
			News.is_deleted == False
		)

		# 分类查询
		if category > 0:
			query = query.filter(News.category_id == category)

		paginate = query.order_by(
			News.sort.asc(),
			News.id.desc()
		).paginate(page, size)
		# 当前分页页码
		data["page"] = paginate.page
		# 上一页页码
		data["prev_num"] = paginate.prev_num
		# 下一页页码
		data["next_num"] = paginate.next_num
		# 是否有上一页
		data["has_prev"] = paginate.has_prev
		# 是否有下一页
		data["has_next"] = paginate.has_next
		# 总页码
		data["pages"] = paginate.pages
		# 总数据量
		data["total"] = paginate.total
		# 当前页数据项
		data['items'] = []
		for news in paginate.items:
			data['items'].append(news.__to_dict__(["id", "title", "read_count", "descript", "created_time", "image_url"]))

	except:
		data = {}

	return data


@jsonrpc_v1.method("News.news(id=Number)")
def list_news(id):
	"""详情页文章信息"""
	data = {}
	try:
		news = News.query.filter(News.is_show==True, News.is_deleted==False, News.id==id).first()
		# 每一次有人访问了文章详情页，就将访问人数加1
		news.read_count += 1
		db.session.commit()
		data = news.__to_dict__(["title", "content", "author", "read_count", "created_time"])
	except:
		pass

	return data